package com.emily.test.utils;

import java.io.IOException;
import java.io.InputStream;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;

/**
 * @author ：zc
 * @date ：Created in 2019/3/21 14:27
 * @description：ftp上传工具
 */

@Component
public class FtpUtil {
    //        Map<String, String> map = new HashMap<>();
//        map.put("code", "0");
//        map.put("msg", "上传文件失败");
//        String fileName = file.getOriginalFilename();
//        logger.info("上传文件:{}", fileName);
//        InputStream inputStream = null;
//        try {
//            inputStream = file.getInputStream();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String filePath = null;
//        Boolean flag = ftpUtil.uploadFile(fileName, inputStream);
//        if (flag == true) {
//            logger.info("上传文件成功!");
//            filePath = ftpUtil.FTP_BASEPATH + fileName;
//            map.put("code", "1");
//            map.put("msg", "上传文件成功");
//        }
//        map.put("path", filePath);
//
//    }

    //ftp服务器ip地址
    private static final String FTP_ADDRESS = "47.150.117.178";
    //端口号
    private static final int FTP_PORT = 21;
    //用户名
    private static final String FTP_USERNAME = "root";
    //密码
    private static final String FTP_PASSWORD = "Haihui@2019";
    //图片路径
    public final String FTP_BASEPATH = "/var/www/img/";

    public boolean uploadFile(String originFileName, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("GBK");
        try {
            int reply;
            ftp.connect(FTP_ADDRESS, FTP_PORT);// 连接FTP服务器
            ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.makeDirectory(FTP_BASEPATH);
            ftp.changeWorkingDirectory(FTP_BASEPATH);
            ftp.storeFile(originFileName, input);
            input.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }

}
